import axios from 'axios'
import qs from 'qs'
import store from '../store/index'
// import * as types from '../store/mutations-type'
import router from '../router/index'

// axios 配置
axios.defaults.timeout = 5000;
axios.defaults.baseURL = window._config.api
    // http request 拦截器
axios.interceptors.request.use(
    config => {
        config.headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
        config.headers['sid'] = store.getters.sid;
        config.data = qs.stringify(config.data);
        return config;
    },
    error => {
        return Promise.reject(error);
    }
);


// http response 拦截器
axios.interceptors.response.use(
    response => {
        switch (response.data.code) {
            case 401:
                store.commit(types.SET_USER_SID, '')
                store.commit(types.SET_USER_INFO, '')
                utils.dialog.confirm({
                    content: "未登录，是否跳转到登录页？",
                    confirm: function() {
                        // router.push({ name: 'login' });
                    }
                });

        }
        // Toast.clear()
        return response;
    },

    error => {
        // Toast.clear()
        return Promise.reject(error.response)
    }
)


export default axios;